# -*- coding: utf-8 -*-
import json
import logging
import os

import thriftpy2 as thriftpy
from thriftpy2.rpc import client_context

from conf.config import BASE_DIR, SERVER_ADDR, SERVER_PORT

logger = logging.getLogger(__name__)


def invoke_push_topic(device_id, data):
    # client = ZookeeperHandler(ZK_HOSTS, SMARTSYS_NOTIFY)
    # ret = client.discover()
    try:
        msg = '{"k":"push","v":[{"type": "status","topic":"%s","data":%s,"from":"sys","msg_id":"1"}], ' \
              '"token":"bbqqk54d31720f1e3100002452183875cb0"}' % (
                  device_id, json.dumps(data))
        # 随机方式实现负载均衡
        server_addr = SERVER_ADDR
        server_port = SERVER_PORT
        # logging.info("要调用的服务：%s %s" % (server_addr, server_port))
        service_thrift = thriftpy.load(os.path.join(BASE_DIR, "idl/notify.thrift"),
                                       module_name="service_thrift")
        with client_context(service_thrift.Notify,
                            server_addr, server_port, timeout=None, socket_timeout=20000) as client:
            r = client.push(msg)
            # logging.info("result:%s" % r)
        return r
    except Exception as e:
        logger.exception(e)


def invoke_push_openid(openid, device_id, mode, msg_type="order-cancel"):
    try:
        msg = '{"k":"notify","v":[{"to":"%s","data":{"id":"%s","mode":"%s"},"from":"sys","msg_id":"1","type":"%s"}],' \
              '"token":"bbqqk54d31720f1e3100002452183875cb0"}' % (
                  openid, device_id, mode, msg_type)
        server_addr = SERVER_ADDR
        server_port = SERVER_PORT
        # logging.info("要调用的服务：%s %s" % (server_addr, server_port))
        service_thrift = thriftpy.load(os.path.join(BASE_DIR, "idl/notify.thrift"),
                                       module_name="service_thrift")
        with client_context(service_thrift.Notify,
                            server_addr, server_port, timeout=None, socket_timeout=20000) as client:
            r = client.push(msg)
            # logging.info("result:%s" % r)
        return r
    except Exception as e:
        logger.exception(e)


if __name__ == "__main__":
    # 往指定openid发消息
    invoke_push_openid("2_opgIMxMJTNX-YxcgWWmX9qL6UDIA", "xxxxxx", "left")
